﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TamTreSoSinh.DBContext;

namespace TamTreSoSinh.Admin
{
    public partial class SettingCustomer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }
            LoadData();
        }

        private void LoadData()
        {
            DBTamTreEntities dbContext = new DBTamTreEntities();

            List<Customer> listCusomter = dbContext.Customers.OrderBy(obj => obj.Priority).ToList();

            GridView1.DataSource = listCusomter;
            GridView1.DataBind();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(@"/Admin/SettingCustomerDetail.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DBTamTreEntities dbContext = new DBTamTreEntities();
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    HiddenField hid = (HiddenField)row.FindControl("hidId");
                    CheckBox chk = (CheckBox)row.FindControl("chkDelete");
                    if (chk.Checked)
                    {
                        int Id = Convert.ToInt32(hid.Value);
                        Customer customer = dbContext.Customers.FirstOrDefault(obj => obj.Id == Id);
                        if (customer != null)
                        {
                            dbContext.Customers.DeleteObject(customer);
                        }
                    }
                }
            }

            dbContext.SaveChanges();
            Response.Redirect(@"/Admin/SettingCustomer.aspx");
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Customer customer = (Customer)e.Row.DataItem;
                if (customer == null)
                {
                    return;
                }
                HiddenField hid = (HiddenField)e.Row.FindControl("hidId");
                hid.Value = customer.Id.ToString();
            }
        }
    }
}